import { Catch } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { makeHttpRequest } from '@midwayjs/core';
import axios from 'axios';
import * as FormData from 'form-data';
import * as multer from '@koa/multer';

// 定义文件类型接口
interface UploadFile {
  filename: string;
  mimeType: string;
  createReadStream(): NodeJS.ReadableStream;
}

// 手动解析formData的函数
async function parseFormData(ctx: Context) {
  return new Promise((resolve, reject) => {
    const upload = multer({
      storage: multer.memoryStorage(),
      limits: {
        fileSize: 10 * 1024 * 1024, // 10MB
        files: 10 // 最多10个文件
      }
    });
    
    upload.any()(ctx, () => {
      resolve({
        files: (ctx as any).files || [],
        body: (ctx as any).body || {}
      });
    });
  });
}

@Catch()
export class NotFoundFilter {
  async catch(err, ctx: Context) {
    if (err && err.message && err.message.includes('Not Found')) {
      const remoteUrl = 'http://apidev.szqerp.com' + ctx.path + (ctx.search || '');
      try {

        // 检查是否是文件上传请求
        const isFileUpload = ctx.headers['content-type']?.includes('multipart/form-data');

        let result;
        
        if (isFileUpload) {
          // 处理文件上传
          const formData = new FormData();
          
          // 获取multer处理后的文件
          let files = (ctx as any).files || [];
          
          // 尝试多种方式获取body数据
          let body = (ctx as any).body || {};
          
          // 如果ctx.body为空，尝试从ctx.request.body获取
          if (!body || Object.keys(body).length === 0) {
            body = ctx.request.body || {};
            console.log('从ctx.request.body获取数据:', body);
          }
          
          // 如果还是空，尝试从原始请求中解析
          if (!body || Object.keys(body).length === 0) {
            console.log('尝试从原始请求解析formData...');
            try {
              const parsedData = await parseFormData(ctx) as { files: any[], body: any };
              files = parsedData.files;
              body = parsedData.body;
              console.log('手动解析后的数据:', { files, body });
            } catch (error) {
              console.error('手动解析formData失败:', error);
            }
          }
          
          console.log('=== 文件上传请求日志 ===');
          console.log('Multer处理后的文件数量:', files.length);
          console.log('Multer处理后的body:', body);
          console.log('ctx.request.body:', ctx.request.body);
          console.log('原始请求头:', ctx.headers);
          
          // 添加文件到formData
          if (files && files.length > 0) {
            for (const file of files) {
              console.log('处理文件:', file.originalname || file.filename);
              formData.append('file', file.buffer || file.createReadStream(), {
                filename: file.originalname || file.filename,
                contentType: file.mimetype || file.mimeType
              });
            }
          }
          
          // 添加其他表单字段，包括type和filename
          if (body) {
            Object.keys(body).forEach(key => {
              if (key !== 'file') { // 避免重复添加文件
                console.log('添加表单字段:', key, body[key]);
                formData.append(key, body[key]);
              }
            });
          }
          
          // 特别处理type和filename字段
          if (body.type) {
            console.log('添加type字段:', body.type);
            formData.append('type', body.type);
          }
          
          if (body.filename) {
            console.log('添加filename字段:', body.filename);
            formData.append('filename', body.filename);
          }
          
          // 如果没有从body中获取到filename，尝试从文件信息中获取
          if (!body.filename && files && files.length > 0) {
            const fileName = files[0].originalname || files[0].filename;
            if (fileName) {
              console.log('从文件信息添加filename字段:', fileName);
              formData.append('filename', fileName);
            }
          }

          // 设置请求头，移除可能导致问题的头部
          const headers = { ...ctx.headers };
          delete headers['content-length']; // 让form-data自动计算长度
          delete headers['host'];


          // 打印最终的formData内容用于调试
          console.log('=== 最终FormData内容 ===');
          console.log('目标URL:', remoteUrl);
          console.log('请求方法:', ctx.method);
          
          // 使用axios转发文件上传请求
          result = await axios({
            method: ctx.method,
            url: remoteUrl,
            data: formData,
            headers: {
              ...headers,
              ...formData.getHeaders() // 添加form-data的边界信息
            },
            maxContentLength: Infinity,
            maxBodyLength: Infinity
          });
          
          console.log('=== 文件上传响应日志 ===');
          console.log('响应状态码:', result.status);
          console.log('响应数据长度:', result.data ? String(result.data).length : 0);


        } else {

          result = await makeHttpRequest(remoteUrl, {
            method: ctx.method,
            data: ctx.request.body,
            headers: ctx.headers,
            dataType: 'text',
          });

          console.log('=== 普通请求响应日志 ===');
          console.log('响应状态码:', result.status);
          console.log('响应数据长度:', result.data ? String(result.data).length : 0);
        }


        let data;
        try {
          data = JSON.parse(String(result?.data));
        } catch {
          data = result?.data; // 不是json就原样返回
        }
        ctx.status = result.status;
        ctx.body = data;
      } catch (e) {
        console.error('=== 请求失败日志 ===');
        console.error('错误信息:', e.message);
        console.error('错误堆栈:', e.stack);
        ctx.status = 502;
        ctx.body = { success: false, message: '代理请求失败', error: e.message };
      }
      return;
    }
    throw err;
  }
}
